<?php
namespace app\client\controller;
use app\common\lib\Redis;
use think\swoole\facade\Task;
use app\common\lib\WxTemplateMessage;

class Bargain extends Base {
    public function __construct() {
        parent::__construct();
    }

    public function viewList() {
        $params = request()->get();
        $pk = isset($params['lastPk']) ? intval($params['lastPk']) : 0;
        $pageSize = isset($params['pageSize']) ? intval($params['pageSize']) : 20;
        $where = [['user_id', '=', $this->userid]];
        
        if($pk > 0) {
            $where[] = ['id', '<', $pk];
        }
        
        $chatList = [];
        
        $rows = model('ChatBargain')->where($where)->order('id desc')->field(['id', 'chat_id', 'stock', 'complete_number', 'end_time'])->limit($pageSize)->select()->toArray();

        if(!empty($rows)) {
            $chatIds = [];
            foreach ($rows as $row) {
                array_push($chatIds, $row['chat_id']);
            }
            
            $chatList = model('Chat')->alias('a')->join('__CHAT_GOODS__ b', 'a.chat_id=b.chat_id')->where(['a.chat_id' => $chatIds])->field(['a.cover', 'a.chat_id', 'b.goods_name'])->select()->toArray();
            if(!empty($chatList)) {
                foreach ($rows as $k => $row) {
                    foreach ($chatList as $chat) {
                        if($chat['chat_id'] == $row['chat_id']) {
                            $rows[$k] = array_merge($chat, $row);
                        }
                    }
                }
            }
        }
        return successResult(['list' => $rows]);
    }
    
    public function start() {
        
        
        $params = request()->post();
        $chatId = isset($params['id']) ? intval($params['id']) : 0;
        if($chatId <= 0) {
            return errorResult('a');
        }
        
        $addressId = isset($params['address']) ? intval($params['address']) : 0;
        if($addressId <= 0) {
            return errorResult('b');
        }
        
        $formId = isset($params['formId']) ? trim($params['formId']) : '';
        /* if($formId === '') {
            return errorResult('c');
        } */
        
        $time = time();
        
        $bargain = model('UserBargain');
        $rs = $bargain->where(['chat_id' =>$chatId, 'user_id' => $this->userid])->field(['status', 'expire_time'])->order('id desc')->find();
        if(!empty($rs) && $rs['status'] == 0 && $rs['expire_time'] > $time) {
            return errorResult('您已发起砍价');
        }
        
        $redis = new Redis();
        $chat = $redis->get(redisChatKey($chatId));
        if(empty($chat)) {
            return errorResult('d');
        }
        
        if(is_string($chat)) {
            $chat = json_decode($chat, true);
        }
        
        if($chat['chat_type'] != 5) {
            return errorResult();
        }
        
        if($chat['start_time'] > $time) {
            return errorResult('活动还没开始');
        }
        
        if($chat['end_time'] <= $time) {
            return errorResult('活动已经结束'.$chatId);
        }
        
        $address = model('DeliveryAddress')->findOne(['id' => $addressId], ['user_id', 'consignee', 'mobile', 'province', 'city', 'district', 'address']);
        if(!$address || $address['user_id'] != $this->userid){
            return errorResult();
        }
        
        $price = $chat['sale_price'] - $chat['bargain_price'];
        
        $bargainAmount = round($price * mt_rand(20, 50) / 100, 2);
        $expireTime = $time + $chat['expire'] * 3600;
        
        $orderData = [
            'order_no' => getOrderNo($this->userid),
            'chat_id' => $chatId,
            'user_id' => $this->userid,
            'bargain_price' => $chat['bargain_price'],
            'current_price' => $chat['sale_price'] - $bargainAmount,
            'start_time' => $time,
            'expire_time' => $expireTime,
            'consignee' => $address['consignee'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'district' => $address['district'],
            'address' => $address['address'],
            'form_id' => $formId
        ];
        
        $bargain->startTrans();
        try {
            $id = $bargain->add($orderData);
            if(!$id) {
                $bargain->rollback();
                return errorResult();
            }
            
            $rs = model('BargainLog')->add(['user_id' => $this->userid, 'bargain_id' => $id, 'amount' => $bargainAmount, 'add_time' => $time]);
            if(!$rs) {
                $bargain->rollback();
                return errorResult();
            }
            $bargain->commit();
            
            return successResult(['id' => $id]);
        } catch (\Exception $e) {
            $bargain->rollback();
            return errorResult($e->getMessage());
        }
        
    }
    
    public function bargain() {
        $id = request()->route('id', 0, 'intval');
        if($id <= 0) {
            return errorResult();
        }
        
        $time = time();
        
        $bargain = model('UserBargain')->findOne(['id' => $id]);
        if(empty($bargain)) {
            return errorResult();
        }
        $bargain['expire'] = $bargain['expire_time'] - $time; //剩余时间
        
        $redis = new Redis();
        $chat = $redis->get(redisChatKey($bargain['chat_id']));
        if(!empty($chat)) {
            $chat = json_decode($chat, true);
        }else{
            $redis->close();
            return errorResult();
        }
        
        
        if($bargain['user_id'] != $this->userid) { //不是本人的
            $bargain['self'] = false;
            $bargain['user'] =$redis->get(redisUserKey($bargain['user_id']));
            $redis->close();
            
            //是否已经砍价
            $rs = model('BargainLog')->findOne(['user_id' => $this->userid, 'bargain_id' => $id], ['id']);
            $bargain['isHelp'] = !empty($rs) ? true : false;
            
        }else{
            $redis->close();
            $bargain['self'] = true;
        }
        
        if($bargain['status'] == 0 && $chat['end_time'] <= $time) { //过期了
            $bargain['status'] = 2;
        }
        
        $chat['isAgent'] = model('Agent')->isAgent($this->userid, $chat['user_id']);
        
             
        return successResult(['bargain' => $bargain, 'chat' => $chat]);
    }
    
    public function help() {
        $id = request()->route('id', 0, 'intval');
        if($id <= 0) {
            return errorResult('a');
        }
        
        $time = time();
        
        
        $chatBargainModel = model('ChatBargain');
        $model = model('UserBargain');
        
        $model->startTrans();
        
        try {
            $bargain = $model->where(['id' => $id])->lock(true)->find();
            if(empty($bargain) || $bargain['user_id'] == $this->userid) {
                $model->rollback();
                return errorResult('b');
            }
            
            $userBargain = $chatBargainModel->where(['chat_id' => $bargain['chat_id']])->lock(true)->find();
            if(empty($userBargain)) {
                $model->rollback();
                return errorResult('砍价已结束');
            }
            if($userBargain['start_time'] > $time) {
                $model->rollback();
                return errorResult('砍价还没开始');
            }
            if($userBargain['end_time'] <= $time) {
                $model->rollback();
                return errorResult('砍价已结束');
            }
            if($userBargain['complete_number'] >= $userBargain['stock']) {
                $model->rollback();
                return errorResult('砍价已结束');
            }
            
            
            if($bargain['status'] != 0 || $bargain['expire_time'] <= $time) {
                $model->rollback();
                return errorResult('砍价已结束');
            }
            
            $updateData = [];
            $offsetAmount = $bargain['current_price'] - $bargain['bargain_price'];
            
            if($offsetAmount <= 1) {
                $amount = $offsetAmount;
                $updateData['status'] = 1;
                $updateData['current_price'] = 0;
            }else{
                $amount = round($offsetAmount * mt_rand(20, 50) / 100, 2);
                $updateData['current_price'] = $bargain['current_price'] - $amount;
            }
            
            $rs = $model->modify(['id' => $id], $updateData);
            if(!$rs) {
                $model->rollback();
                return errorResult('c');
            }
            
            $rs = model('BargainLog')->add(['user_id' => $this->userid, 'bargain_id' => $id, 'amount' => $amount, 'add_time' => $time]);
            if(!$rs) {
                $model->rollback();
                return errorResult('d');
            }
            
            if(isset($updateData['status']) &&$updateData['status'] == 1) {
                $redis = new Redis();
                $chat = $redis->get(redisChatKey($bargain['chat_id']));
                $redis->close();
                if(empty($chat)) {
                    $model->rollback();
                    return errorResult('e');
                }
                
                $chat = json_decode($chat, true);
                
                /* $goods = model('ChatBargain')->findOne(['chat_id' => $bargain['chat_id']], ['end_time', 'goods_name', 'sale_price']);
                if(empty($goods)) {
                    $model->rollback();
                    return errorResult('砍价已结束');
                } */
                $orderData = [
                    'user_id' => $bargain['user_id'],
                    'order_no' => $bargain['order_no'],
                    'order_type' => 2,
                    'store_id' => $chat['user_id'],
                    'quantity' => 1,
                    'amount' => $bargain['bargain_price'],
                    'consignee' => $bargain['consignee'],
                    'mobile' => $bargain['mobile'],
                    'province' => $bargain['province'],
                    'city' => $bargain['city'],
                    'district' => $bargain['district'],
                    'address' => $bargain['address'],
                    'create_time' => $bargain['start_time']
                ];
                
                if($bargain['bargain_price'] > 0) { //需要支付
                    $orderData['status'] = 1;
                }else {
                    $orderData['status'] = 2;
                    $orderData['pay_status'] = 1;
                }
                
                $orderId = model('Order')->add($orderData);
                if(!$orderId) {
                    $model->rollback();
                    return errorResult('sos');
                }
                
                $rs = model('OrderGoods')->add(['order_id' => $orderId, 'chat_id' => $bargain['chat_id'], 'cover' => $chat['cover'], 'goods_name' => $chat['goods_name'], 'goods_no' => $chat['goods_no'], 'price' => $chat['sale_price'], 'quantity' => 1]);
                if(!$rs) {
                    $model->rollback();
                    return errorResult('dodo');
                }
                
                $openId = model('User')->where(['user_id' => $bargain['user_id']])->value('openid');
                if(empty($openId)) {
                    $model->rollback();
                    return errorResult('vivi');
                }
                
                $rs = $chatBargainModel->modify(['chat_id' => $bargain['chat_id']], ['complete_number' => $userBargain['complete_number'] + 1]);
                if(!$rs) {
                    $model->rollback();
                    return errorResult('vivi');
                }
                
                $goods = ['goods_name' => $chat['goods_name'], 'end_time' => $chat['end_time'], 'sale_price' => $chat['sale_price']];
                
                if(!empty($bargain['form_id'])) {
                    Task::async(function() use($bargain, $goods, $openId) {
                        $data = [
                            $goods['goods_name'],
                            $goods['sale_price'] . '元',
                            ($goods['sale_price'] - $bargain['bargain_price']) . '元',
                            $bargain['bargain_price'] . '元',
                            $bargain['bargain_price'] > 0 ? date('Y-m-d H:i:s', $goods['end_time']) : '无需支付'
                        ];
                        $RS = WxTemplateMessage::send($openId, 'yLmxopojUb5kqi4kqQSmYD6J06pwk9JgaZgMUBpQdXk', $bargain['form_id'], [], 'keyword5.DATA', $data);
                    });
                }
                
            }
            
            $model->commit();
            
            return successResult(['amount' => $amount]);
            
        } catch (\Exception $e) {
            $model->rollback();
            return errorResult($e->getMessage());
        }
        
    }
    
    public function helpLog() {
        $id = request()->route('id', 0, 'intval');
        if($id <= 0) {
            return errorResult();
        }
        
        $logs = model('BargainLog')->findAll(['bargain_id' => $id], ['amount', 'user_id']);
        if(!empty($logs)) {
            $logs = array_reverse($logs);
            $userIds = [];
            foreach ($logs as $log) {
                array_push($userIds, redisUserKey($log['user_id']));
            }
            
            $redis = new Redis();
            $userList = $redis->mget($userIds);
            foreach ($logs as &$log) {
                $log['user'] = array_shift($userList);
            }
        }
        
        return successResult(['list' => $logs]);
    }
}



























